from models import Connections
from models import Server
from django.contrib import admin
from django.db import models
from django.contrib.admin.filterspecs import FilterSpec, DateFieldFilterSpec
from django.utils.encoding import smart_unicode
from django.utils.translation import ugettext as _
from filterspecs import DateRangeFilterSpec
import datetime


class MyDateFieldFilterSpec(DateFieldFilterSpec):
    def __init__(self, f, request, params, model, model_admin,
                 field_path=None): 
        super(DateFieldFilterSpec, self).__init__(f, request, params, model,
                                                  model_admin,
                                                  field_path=field_path)

        self.field_generic = '%s__' % self.field_path

        self.date_params = dict([(k, v) for k, v in params.items()
                                 if k.startswith(self.field_generic)])

        now = datetime.datetime.now();
        today = datetime.date.today()
        hour_ago = now - datetime.timedelta(hours=1)
        tree_hours_ago = now - datetime.timedelta(hours=3)
        tree_days_ago = today - datetime.timedelta(days=3)
        week_ago = today - datetime.timedelta(days=7)
        month_ago = today - datetime.timedelta(days=30)
        tree_months_ago = today - datetime.timedelta(days=90)
        today_str = isinstance(self.field, models.DateTimeField) \
                    and today.strftime('%Y-%m-%d 23:59:59') \
                    or today.strftime('%Y-%m-%d')

        self.links = (
            (_('Any date'), {}),
            (_('Today'), {'%s__year' % self.field_path: str(today.year),
                       '%s__month' % self.field_path: str(today.month),
                       '%s__day' % self.field_path: str(today.day)}),
            (_('Past hour'), {'%s__gte' % self.field_path:
                                    hour_ago.strftime('%Y-%m-%d %H:%M:%S'),
                             '%s__lte' % self.field_path: today_str}),
            (_('Past 3 hours'), {'%s__gte' % self.field_path:
                                    tree_hours_ago.strftime('%Y-%m-%d %H:%M:%S'),
                             '%s__lte' % self.field_path: today_str}),
            (_('Past 3 days'), {'%s__gte' % self.field_path:
                                    tree_days_ago.strftime('%Y-%m-%d'),
                             '%s__lte' % self.field_path: today_str}),
            (_('Past week'), {'%s__gte' % self.field_path:
                                    week_ago.strftime('%Y-%m-%d'),
                             '%s__lte' % self.field_path: today_str}),
            (_('Past month'), {'%s__gte' % self.field_path:
                                    month_ago.strftime('%Y-%m-%d'),
                             '%s__lte' % self.field_path: today_str}),
            (_('Past 3 months'), {'%s__gte' % self.field_path:
                                    tree_months_ago.strftime('%Y-%m-%d'),
                             '%s__lte' % self.field_path: today_str}),
            (_('This month'), {'%s__year' % self.field_path: str(today.year),
                             '%s__month' % self.field_path: str(today.month)}),
            (_('This year'), {'%s__year' % self.field_path: str(today.year)})
        )

FilterSpec.filter_specs.insert(1,
    (lambda f: hasattr(f, 'date_range_filter'), DateRangeFilterSpec))

FilterSpec.filter_specs.insert(0, (lambda f: getattr(f, 'my_date_filter', False),MyDateFieldFilterSpec))

class ConnectionsAdmin(admin.ModelAdmin):
    list_display = ('id', 'honeypot', 'session', 'ip', 'port', 'client', 'login', 'password', 'authenticated', 'commands', 'my_start_time', 'my_finish_time', 'country')
    list_filter = ['honeypot', 'client', 'start_time', 'finish_time']
    search_fields = ['ip', 'session', 'login', 'password', 'authenticated', 'commands', 'country']
    date_hierarchy = 'start_time'
    
    def my_start_time(self, obj):
            return obj.start_time.strftime('%Y-%m-%d %H:%M:%S')
    my_start_time.admin_order_field = 'start_time' 
    my_start_time.short_description = 'Start Time'
    def my_finish_time(self, obj):
            return obj.finish_time.strftime('%Y-%m-%d %H:%M:%S')
    my_finish_time.admin_order_field = 'finish_time' 
    my_finish_time.short_description = 'Finish Time'
    

class ServerAdmin(admin.ModelAdmin):
    list_display = ('id', 'name', 'ip','port', 'start_time', 'configuration')
    list_filter = ['name', 'ip', 'start_time']
    search_fields = ['configuration']
    date_hierarchy = 'start_time'
    
admin.site.register(Connections, ConnectionsAdmin)
admin.site.register(Server, ServerAdmin)
